package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserBankParam(param map[string]interface{}) (*models_main.UserBank, error) {
	fName := "GetUserBankParam"
	o := &models_main.UserBank{}
	table := mysql.GetRTable(&models_main.UserBank{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetUserBanksParam(param map[string]interface{}, order string, page, size int) ([]*models_main.UserBank, error) {
	fName := "GetUserBanksParam"
	o := make([]*models_main.UserBank, 0)
	table := mysql.GetRTable(&models_main.UserBank{})
	mysql.Condition(table, param, "", order, page, size)
	err := table.Find(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertUserBank(session *gorm.DB, bank *models_main.UserBank) error {
	fName := "InsertUserBank"
	if session == nil {
		session = global.GetX()
	}
	err := session.Create(bank).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserBank(session *gorm.DB, columns []string, bank *models_main.UserBank) error {
	fName := "UpdateUserBank"
	if session == nil {
		session = global.GetX()
	}
	err := session.Where("id = ?", bank.Id).Select(columns).Updates(bank).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func GetUserAddressParam(param map[string]interface{}) (*models_main.UserAddress, error) {
	fName := "GetUserAddressParam"
	o := &models_main.UserAddress{}
	table := mysql.GetRTable(&models_main.UserAddress{})
	mysql.Condition(table, param, "", "", 0, 0)
	err := table.Find(o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func InsertUserAddress(session *gorm.DB, address *models_main.UserAddress) error {
	fName := "InsertUserAddress"
	if session == nil {
		session = global.GetX()
	}
	err := session.Create(address).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserAddress(columns []string, address *models_main.UserAddress) error {
	fName := "UpdateUserAddress"
	err := global.GetX().Where("id = ?", address.Id).Select(columns).Updates(address).Error
	if err != nil {
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
